<template>
  <div class="screen">
    <div v-if="defaultSearch.length" class="defaultScreen">
      <span v-for="item in defaultSearch.filter((item, index) => index < 3)" :key="item.id" :class="{ tabsItem: true, curr: defaultSearchCommand === item.id }" @click="toDefaultSearch(item.id, 'defaultSearch')">{{ item.searchName }}</span>
      <el-dropdown v-if="defaultSearch.length > 3" placement="bottom" size="medium" @command="toDefaultSearch($event, 'defaultSearch')">
        <span class="el-dropdown-link" style="line-height: 14px; font-size: 14px">
          更多
          <i class="el-icon-arrow-down el-icon--right" />
        </span>
        <el-dropdown-menu slot="dropdown" class="screenMoreList">
          <el-dropdown-item v-for="item in defaultSearch.filter((item, index) => index >= 3)" :key="item.id" :command="item.id">{{ item.searchName }}</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
    <el-dropdown v-if="customSearch.length" placement="bottom" size="medium" @command="toDefaultSearch($event, 'customSearch')">
      <span class="el-dropdown-link" style="line-height: 14px; font-size: 14px">
        自定义
        <i class="el-icon-arrow-down el-icon--right" />
      </span>
      <el-dropdown-menu slot="dropdown" class="screenMoreList">
        <el-dropdown-item v-for="item in customSearch" :key="item.id" :command="item.id">{{ item.searchName }}</el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>
    <el-popover placement="bottom-start" width="580" trigger="click">
      <div class="searchFormBox">
        <el-form ref="dynamicForm" :model="searchForm" class="searchForm" size="medium">
          <el-row v-for="(item, index) in searchForm.dynamicQueryBos" :key="index" :gutter="12">
            <el-col :span="10">
              <el-form-item prop="prop">
                <el-select v-model="searchForm.dynamicQueryBos[index].name" clearable value-key="id" :placeholder="$t('table.pleaseSelect')" @change="updateDynamicProp($event, index)">
                  <el-option v-for="el in searchFormOption.templateOption" :key="el.id" :label="el.nameValue" :value="el.name" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item prop="operator">
                <el-select v-model="searchForm.dynamicQueryBos[index].operator" :placeholder="$t('table.pleaseSelect')">
                  <el-option v-for="el in searchFormOption.operatorOptions" :key="el.value" :label="el.label" :value="el.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <!-- // type: 1, //  条件类型(1:文本框、2:下拉框、3:日期控件、4:时间控件、5:日期时间控件、6:多记录文本、) -->
            <el-col :span="10">
              <el-form-item prop="value">
                <el-input v-if="!searchForm.dynamicQueryBos[index].prop" v-model.trim="searchForm.dynamicQueryBos[index].value" clearable :placeholder="$t('table.pleaseFillIn')" class="formItem" />
                <el-select v-else-if="searchForm.dynamicQueryBos[index].prop.type === 2" v-model="searchForm.dynamicQueryBos[index].value" clearable class="formItem" :placeholder="$t('table.pleaseSelect')" @change="updateValueName($event, searchForm.dynamicQueryBos[index], dataSourceValues[searchForm.dynamicQueryBos[index].prop.dataSourceValue])">
                  <el-option v-for="el in dataSourceValues[searchForm.dynamicQueryBos[index].prop.dataSourceValue]" :key="el.id" :label="el.text" :value="el.id">
                    <span style="float: left">{{ el.id }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{ el.text }}</span>
                  </el-option>
                </el-select>
                <el-date-picker v-else-if="searchForm.dynamicQueryBos[index].prop.type === 3" v-model="searchForm.dynamicQueryBos[index].value" class="formItem" :value-format="searchForm.dynamicQueryBos[index].prop.datePrecision" :format="searchForm.dynamicQueryBos[index].prop.datePrecision" type="date" :placeholder="$t('table.pleaseSelect')" />
                <el-time-select v-else-if="searchForm.dynamicQueryBos[index].prop.type === 4" v-model="searchForm.dynamicQueryBos[index].value" class="formItem" :value-format="searchForm.dynamicQueryBos[index].prop.datePrecision" :format="searchForm.dynamicQueryBos[index].prop.datePrecision" :placeholder="$t('table.pleaseSelect')" />
                <el-date-picker v-else-if="searchForm.dynamicQueryBos[index].prop.type === 5" v-model="searchForm.dynamicQueryBos[index].value" class="formItem" :value-format="searchForm.dynamicQueryBos[index].prop.datePrecision" :format="searchForm.dynamicQueryBos[index].prop.datePrecision" type="datetime" :placeholder="$t('table.pleaseSelect')" />
                <el-input v-else-if="searchForm.dynamicQueryBos[index].prop.type === 6" v-model.trim="searchForm.dynamicQueryBos[index].value" clearable class="formItem" type="textarea" :placeholder="$t('table.pleaseFillIn')" @focus="getHigh($event)" @blur="getNormal($event)" />
                <el-input v-else v-model.trim="searchForm.dynamicQueryBos[index].value" clearable :placeholder="$t('table.pleaseFillIn')" class="formItem" />
              </el-form-item>
            </el-col>
          </el-row>
          <div class="dividerColumn" style="width: 552px; left: -32px; margin: 6px 0 20px" />
          <div class="searchLabelBox">
            <el-form-item class="marginItem" :label="$t('setSearchConfig.searchLabel')" prop="name" label-width="80px" :rules="[{ required: true, message: $t('setSearchConfig.pleaseFillInName') }]">
              <el-input v-model.trim="searchForm.name" />
            </el-form-item>
          </div>
        </el-form>
        <div class="searchFormButtons">
          <div class="left">
            <el-button size="medium" @click="saveCommon">保存</el-button>
          </div>
          <div class="right">
            <el-button size="medium" @click="resetDynamicForm">重置</el-button>
            <el-button type="primary" size="medium" @click="toDynamicSearch()">搜索</el-button>
          </div>
        </div>
      </div>
      <span slot="reference" class="tabsItem" style="line-height: 14px; font-size: 14px">
        搜索项
        <i class="el-icon-arrow-down el-icon--right" />
      </span>
    </el-popover>
  </div>
</template>
<script>
import Vue from 'vue'
import { queryconditionList, queryDictSelect, saveCommonCondition, queryCommonCondition } from '@/api/advanced'
export default {
  name: 'DefaultScreen',
  props: {
    menuCode: {
      type: String,
      require: true,
    },
    tableCode: {
      type: String,
      require: true,
    },
    // customSearch: {
    //   type: Array,
    //   require: false,
    //   default: () => [],
    // },
    defaultSearch: {
      type: Array,
      require: false,
      default: () => [],
    },
  },
  data() {
    const obj = {
      value: null,
      name: null,
      operator: 'EQ',
      prop: null,
    }
    const templateOption = []
    for (let i = 0; i < 6; i++) {
      const d = Object.assign({}, obj)
      templateOption.push(d)
    }
    return {
      templateItemObj: JSON.stringify(obj),
      templateItem: JSON.stringify(templateOption),
      searchCommand: null,
      defaultSearchCommand: null,
      searchFormOption: {
        operatorOptions: [
          {
            value: 'EQ',
            label: this.$t('setSearchConfig.EQ'),
          },
          {
            value: 'NE',
            label: this.$t('setSearchConfig.NE'),
          },
          {
            value: 'GT',
            label: this.$t('setSearchConfig.GT'),
          },
          {
            value: 'GE',
            label: this.$t('setSearchConfig.GE'),
          },
          {
            value: 'LT',
            label: this.$t('setSearchConfig.LT'),
          },
          {
            value: 'LE',
            label: this.$t('setSearchConfig.LE'),
          },
          {
            value: 'LIKE',
            label: this.$t('setSearchConfig.LIKE'),
          },
          {
            value: 'IN',
            label: this.$t('setSearchConfig.IN'),
          },
        ],
        templateOption: [],
      },
      customSearch: [],
      dataSourceValues: {},
      searchForm: {
        name: '',
        dynamicQueryBos: templateOption,
      },
    }
  },
  mounted() {
    this.queryCommonCondition()
    this.queryList()
  },
  methods: {
    getDynamicQueryBosData() {
      console.log(JSON.stringify(this.searchForm.dynamicQueryBos))
      return this.searchForm.dynamicQueryBos
        .filter((item) => item.prop && item.value)
        .map((item) => {
          return {
            ...item.prop,
            name: item.prop.name,
            operator: item.operator,
            value: item.value,
            // type: item.prop.type,
            // dataSource: item.prop.dataSource,
            // dataSourceValue: item.prop.dataSourceValue,
            // valueName: item.valueName,
            // valueType: item.prop.valueType,
            // datePrecision: item.prop.datePrecision,
          }
        })
    },
    async queryCommonCondition() {
      const params = {
        menuCode: this.menuCode,
        tableCode: this.tableCode,
      }
      const { data } = await queryCommonCondition(params)
      this.customSearch = data
    },
    saveCommon() {
      this.$refs['dynamicForm'].validate((valid) => {
        if (valid) {
          const dynamicQueryBos = this.getDynamicQueryBosData()
          const data = {
            commonConditionReqBOList: dynamicQueryBos,
            menuCode: this.menuCode,
            tableCode: this.tableCode,
            searchName: this.searchForm.name,
          }
          if (data.commonConditionReqBOList.length === 0) {
            this.$message.error('最少填写完整一项')
            return false
          }
          // 保存时做判断如果存在同名的自定义搜索，变更为修改此搜索
          const find = this.customSearch.find((item) => item.searchName === data.searchName)
          if (find) {
            data.id = find.id
          }
          saveCommonCondition(data).then((res) => {
            this.queryCommonCondition()
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    searchData() {
      const data = {
        dynamicQueryBos: [],
        commonId: this.searchCommand,
      }
      if (!data.commonId) {
        data.dynamicQueryBos = this.getDynamicQueryBosData()
      }
      this.$emit('toSearch', data)
    },
    toDynamicSearch() {
      this.searchCommand = ''
      this.searchData()
    },
    resetDynamicForm() {
      this.searchForm.dynamicQueryBos = JSON.parse(this.templateItem)
    },
    updateValueName(ev, row, opt) {
      row.valueName = opt.find((item) => item.id === ev).text
    },
    async updateDynamicProp(ev, index, val) {
      const row = this.searchForm.dynamicQueryBos[index]
      row.prop = this.searchFormOption.templateOption.find((item) => item.name === ev)
      console.log(row)
      if (row.prop.type === 2) {
        if (!this.dataSourceValues[row.prop.dataSourceValue]) {
          const { data } = await queryDictSelect({ url: row.prop.dataSourceValue })
          this.dataSourceValues[row.prop.dataSourceValue] = data || [] // ev.dataSourceValue
        }
        this.$forceUpdate()
        // Vue.set(this.searchForm.dynamicQueryBos, index, { ...row, prop: { ...row.prop }})
      }
      if (!val) {
        row.value = null
      }
    },
    queryList() {
      queryconditionList({ menuCode: this.menuCode, tableCode: this.tableCode }).then(({ data }) => {
        // console.log(res)
        this.searchFormOption.templateOption = data
      })
    },
    toDefaultSearch(str, type) {
      const searchCommandItem = this[type].find((item) => item.id === str)
      if (type === 'customSearch') {
        this.searchCommand = str
        this.defaultSearchCommand = null
      } else {
        this.defaultSearchCommand = str
        this.searchCommand = null
      }
      const commSql = JSON.parse(searchCommandItem.commSql)
      const dynamicQueryBos = commSql.map((item) => {
        return {
          name: item.name,
          operator: item.operator,
          value: item.value,
          prop: {
            name: item.name,
            dataSource: item.dataSource,
            dataSourceValue: item.dataSourceValue,
            dynamicQueryOperatorType: item.dynamicQueryOperatorType,
            dynamicQueryValueType: item.dynamicQueryValueType,
            type: item.type,
            valueType: item.valueType,
          },
        }
      })
      if (dynamicQueryBos.length < 6) {
        for (let i = dynamicQueryBos.length; i < 6; i++) {
          dynamicQueryBos.push(JSON.parse(this.templateItemObj))
        }
      }
      for (let i = 0; i < dynamicQueryBos.length; i++) {
        const el = dynamicQueryBos[i]
        if (el.prop && el.prop.type === 2) {
          this.updateDynamicProp(el.name, i, true)
        }
      }
      this.searchForm.dynamicQueryBos = dynamicQueryBos
      this.searchData()
    },
  },
}
</script>
